﻿using Core;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using System.Data.SqlClient;
using System.Data;

namespace DAL
{
    public class ChapterDAL : BaseDAL
    {
        #region 地区表导入
        /// <summary>
        /// 章节表导入
        /// </summary>
        /// <returns></returns>
        public bool GetChapter(int id)
        {
            using (WebClient wc = new WebClient())
            {
                wc.Encoding = System.Text.Encoding.GetEncoding("utf-8");
                string strCptr = string.Empty;
                try
                {
                    strCptr = wc.DownloadString(ConfigHelper.GetConfigString("RemoteUrl") + "/Ayyfford/GetChapter/" + id);
                }
                finally
                {
                    wc.Dispose();
                }
                if (!string.IsNullOrWhiteSpace(strCptr))
                {
                    var lCptr = JsonConvert.DeserializeObject<List<Model.Chapter>>(strCptr);

                    #region 数据入库
                    using (var conn = new SqlConnection(connection))
                    {
                        conn.Open();
                        IDbTransaction transaction = conn.BeginTransaction();
                        try
                        {
                            lCptr.ForEach(ptr =>
                            {
                                conn.Execute("if not exists (select ID from Chapter where ID=" + ptr.ID + @")  
                                                begin 
                                                    insert into Chapter(ID,FatherID,PointName,Content,TeachingMaterialID) values (@ID,@FatherID,@PointName,@Content,@TeachingMaterialID)
                                                end
                                                    else
                                                begin
                                                    update Chapter set FatherID=@FatherID,PointName=@PointName,Content=@Content,TeachingMaterialID=@TeachingMaterialID where ID=@ID
                                                end", ptr, transaction);
                            });
                            transaction.Commit();
                            return true;
                        }
                        catch (Exception ex)
                        {
                            transaction.Rollback();
                            Log.errorlog(ex);
                        }
                        conn.Close();
                    }
                    #endregion
                }
            }
            return false;
        }
        #endregion
    }
}
